package cn.lzd.mr.case10;

import cn.lzd.mr.PathUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 2019/7/16
 * 看第1列数据和其它第1列数据是否有重合，有重合就合并
 */
public class Case10MR3 {

    static class Mp extends Mapper<LongWritable, Text, Text, Text> {
        Text outKey = new Text();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String str = value.toString();
            String[] split = str.trim().split(",", -1);
            for (String s : split) {
                outKey.set(s);
                context.write(outKey, value);
            }
        }
    }

    static class Rd extends Reducer<Text, Text, Text, NullWritable> {
        Text outkey = new Text();

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuffer bf = new StringBuffer();
            for (Text value : values) {
                StringBuffer buffer = new StringBuffer();
                String[] arr = value.toString().split(",", -1);
                for (String s : arr) {
                    buffer.append(s).append("+");
                }

                bf.append(buffer.toString()).append(",");
            }

            String bs = bf.toString();
            bs = bs.substring(0, bs.length() - 1);

            outkey.set(bs);
            context.write(outkey, NullWritable.get());
        }
    }

    public static void main(String[] args) throws Exception {

        String inpath = PathUtil.getpath("case10") + "/*";
        String outpath = PathUtil.getpath("case10") + "out2/";

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);
        job.setJarByClass(Case10MR3.class);

        job.setMapperClass(Mp.class);
        job.setReducerClass(Rd.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        job.setGroupingComparatorClass(GroupComparator10.class);

        FileInputFormat.addInputPath(job, new Path(inpath));
        FileOutputFormat.setOutputPath(job, new Path(outpath));

        job.waitForCompletion(true);

    }
}
